from typing import List

from fastapi.responses import JSONResponse
from fastapi import APIRouter
from app.schemas.chat import Message, HistoryMessage
from app.services import chat, history
from app.core import schedule
import logging

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/messages")
def get_chat_response(message_data: Message):
    """
    对话接口
    :param message_data:
    :return:
    """
    try:
        user_name = message_data.userName
        message = message_data.message
        lang = chat.detect_language(message)
        intent = chat.detect_intent(message)

        if intent == "schedule":
            response = chat.extract_event_details(message, lang)
            logger.info("提取事件详情: %s", response)
            if not response.get("success", True):
                logger.warning("提取事件详情时出现错误: %s", response)
                return response
            subject = response.get("Subject")
            start = response.get("Start Time")
            end = response.get("End Time")
            location = response.get("Location")
            logger.info("事件详情 - 主题: %s, 开始时间: %s, 结束时间: %s, 地点: %s", subject, start, end, location)
            schedule.schedule_event_sync(subject=subject, start=start, end=end, location=location, busy=0)
            logger.info("日程已创建: %s (%s - %s) @ %s", subject, start, end, location)
            reply = f"Schedule Created: {subject} ({start} - {end}) @ {location}"
            history.save_chat_history(user_name=user_name, message=message, reply=reply)
            return {
                "success": True,
                "message": reply
            }

        reply = chat.get_ai_response(message, lang)
        logger.info("获取AI回复: %s", reply)
        history.save_chat_history(user_name=user_name, message=message, reply=reply)
        return {"success": True, "message": reply}
    except Exception as e:
        logger.error("获取AI回复过程中出现错误: %s", str(e))
        raise

@router.post("/history", response_model=List[dict])
def get_history_message(history_message_data: HistoryMessage):
    """
    获取历史对话记录
    """
    username = history_message_data.userName
    print(username)

    # 如果用户名为空，直接返回空列表
    if not username:
        return JSONResponse(status_code=200, content={"message": "No username provided. Returning empty history.", "data": []})

    history_data = history.read_chat_history(user_name=username)

    # 返回历史记录，最多10条
    return JSONResponse(status_code=200, content={"message": "History fetched successfully.", "data": history_data[-10:]})


